package com.weme.live.activity

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.activity.OnBackPressedCallback
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.weme.common.arouter.ARouterHelper.KEY_ROOM_BEAN
import com.weme.common.arouter.ARouterPaths
import com.weme.common.arouter.LiveRoomBean
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.dialog.GiftDialog
import com.weme.common.dialog.GiftDialogCallback
import com.weme.common.util.*
import com.weme.live.databinding.ActivityLiveRoomBinding
import com.weme.live.ext.*
import com.weme.live.fragment.MyPagerAdapter
import com.weme.live.view.GuideConsumptionView
import com.weme.live.viewmode.LiveViewMode
import dev.kratos.api.user_server.v1.GetUserInfoRequest
import dev.kratos.api.user_server.v1.GiftInfo
import dev.kratos.api.user_server.v1.SendGiftRequest
import io.agora.chat.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Route(path = ARouterPaths.LIVE_ROOM_ACTIVITY)
class LiveRoomActivity : BaseMvvmActivity<ActivityLiveRoomBinding, LiveViewMode>(),
    KeyboardVisibilityListenerCallback {


    lateinit var keyboardVisibilityListener: KeyboardVisibilityListener
    var giftDialog: GiftDialog? = null
    var guideConsumptionView: GuideConsumptionView? = null


    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).keyboardEnable(false).init()
        enableHideSoftInput = false //禁止点击外部关闭软键盘 解决软键盘弹出无法发送消息
        window.setFlags(
            WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE
        )
        initInitData()
        initConifg()
        viewModeObserve()
        initViewpager2()
        viewModel.getAccountInfo() //获取下自己的信息
        setOnclick()

    }

    override fun onResume() {
        super.onResume()
        mBinding.svgaGift.playSVGAFromAssets("gift_button_animation")
    }

    override fun onPause() {
        super.onPause()
        mBinding.svgaGift.stopAnimation()
        mBinding.svgaGift.clear()
    }

    override fun onBackPressed() {
        viewModel.navigateToReviewPageLiveData.postValue("")
    }

    private fun initInitData() {
        intent.extras?.apply {
            val liveRoomBean: LiveRoomBean = this.getSerializable(KEY_ROOM_BEAN) as LiveRoomBean
            liveRoomBean.let {
                viewModel.anchorId = liveRoomBean.userId
                if (viewModel.anchorId != 0L) { //获取主播信息
                    viewModel.getLiveUserInfo(GetUserInfoRequest.newBuilder().addUids(viewModel.anchorId).build())
                } else {
                    if (BuildConfig.DEBUG) {
                        showToast("没有传入主播id")
                    }
                }
                viewModel.isMatch = liveRoomBean.matchMessage != null
                viewModel.isIncoming = it.isIncoming

                if (viewModel.isMatch) {
                    try {
                        liveRoomBean.matchMessage?.let {
                            viewModel.isFictitious = it.matchedUser.isVirtual == 1
                            if (viewModel.isFictitious) { //如果是营销主播
                                oneselfCamera() //打开自己的摄像头
                                playVideo(it.matchedUser.video) //播放营销视频
                            } else {
                                if (!TextUtils.isEmpty(liveRoomBean.rtcToken)) { //加入房间
                                    CoroutineScope(Dispatchers.Default).launch {
                                        initVideo(liveRoomBean.rtcToken, liveRoomBean.channelName)
                                    }
                                    viewModel.channelName = liveRoomBean.channelName
                                } else {
                                    viewModel.getRtcToken()
                                }
                                if (!TextUtils.isEmpty(liveRoomBean.chatRoomId)) {
                                    chatRoomId = liveRoomBean.chatRoomId
                                    if (!TextUtils.isEmpty(chatRoomId)) { //如果有roomid 加入聊天室
                                        addChat()
                                    }
                                } else {
                                    viewModel.getChannelInfo()
                                }
                            }
                        }
                    } catch (e: Exception) {
                        Log.e("liveroom", "liveRoomBean = null ")
                    }
                } else {
                    if (!TextUtils.isEmpty(liveRoomBean.rtcToken)) { //加入房间
                        CoroutineScope(Dispatchers.Default).launch {
                            initVideo(liveRoomBean.rtcToken, liveRoomBean.channelName)
                        }
                        viewModel.channelName = liveRoomBean.channelName
                    } else {
                        viewModel.getRtcToken()
                    }
                    if (!TextUtils.isEmpty(liveRoomBean.chatRoomId.trim())) {
                        Log.e("chatRoom", "live" + liveRoomBean.chatRoomId)
                        chatRoomId = liveRoomBean.chatRoomId
                        addChat()
                    } else {
                        viewModel.getChannelInfo()
                    }
                }
            }
            viewModel.liveRoomBean = liveRoomBean
        }
    }

    private fun initViewpager2() {
        val adapter = MyPagerAdapter(this)
        mBinding.vp2.adapter = adapter
        mBinding.vp2.setCurrentItem(1, false)
        mBinding.vp2.isUserInputEnabled = false // 禁止滑动翻页
        keyboardVisibilityListener = KeyboardVisibilityListener(this)
        keyboardVisibilityListener.addVisibilityListener(this)
        mBinding.vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (position == 0) {
                    mBinding.imGift.setImageResource(com.example.resources.R.mipmap.icon_live_gift)
                }
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { // 当页面滚动时调用，可以获取当前页面索引、偏移百分比和像素
                // 在这里可以执行一些与滚动有关的操作
            }

            override fun onPageScrollStateChanged(state: Int) { // 当页面滚动状态发生变化时调用，state 是滚动状态的值
                // 在这里可以处理滚动状态变化时的逻辑
            }
        })
    }


    private fun setOnclick() {

        mBinding.imGift.setOnClickListener {
            if (mBinding.imGift.isSelected) {
                viewModel.sendMsgLiveData.postValue("")
            } else {
                if (null == giftDialog) {
                    giftDialog = GiftDialog("", object : GiftDialogCallback {
                        override fun sendGiftInfo(giftInfo: GiftInfo) {
                            viewModel.sendGift(SendGiftRequest.newBuilder().setGiftId(giftInfo.id).setGiftNum(1).setUid(viewModel.anchorId).build())
                            giftDialog?.dismiss()
                        }
                    })

                }
                giftDialog?.show(this.supportFragmentManager, "")

            }

        }
    }

    override fun onDestroy() {
        mBinding.playerView.stopPlay()
        mBinding.playerView.release()

        viewModel.compositeDisposable.dispose()
        rtcEngineDestroy()
        outRoomChat()
        keyboardVisibilityListener.removeVisibilityListener(this)
        if (viewModel.isFictitious) {
            stopPlay() //关闭营销视频
        }

        super.onDestroy()
    }


    override fun getViewModelClass(): Class<LiveViewMode> = LiveViewMode::class.java
    fun getViewBinding(): ActivityLiveRoomBinding = mBinding
    fun getViewModel(): LiveViewMode = viewModel
    var isKeyboardVisible = false


    override fun onKeyboardVisibilityChanged(isVisible: Boolean, keyboardHeight: Int) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).keyboardEnable(false)
            .init()
        mBinding.vp2.updateLayoutParams<ConstraintLayout.LayoutParams> {
            if(isVisible){
                bottomMargin = keyboardHeight - 88
            }else{
                bottomMargin = keyboardHeight
            }

        }
        isKeyboardVisible = isVisible
        mBinding.imGift.isSelected = isVisible
        if (isVisible) {
            viewModel.edTextView?.apply {
                mBinding.imGift.alpha = if (this.text.toString().isEmpty()) 0.5f else 1f
            }


            mBinding.draggableView.gone() //  guideConsumptionView?.gone()
        } else {
            mBinding.imGift.alpha = 1f
            mBinding.draggableView.visible() //  guideConsumptionView?.visible()
            mBinding.draggableView.fadeIn() //guideConsumptionView?.fadeIn()
        }
        viewModel.showKeyboardLiveData.postValue(!isVisible)

    }


    fun navigateToPage() {
        if (isKeyboardVisible) {
            return
        }
        if (mBinding.draggableView.visibility == View.VISIBLE) {
            viewModel.screenClearLiveData.postValue(true)
            mBinding.draggableView.gone()
        } else {
            viewModel.screenClearLiveData.postValue(false)
            mBinding.draggableView.visible()
        } // mBinding.vp2.currentItem = if (mBinding.vp2.currentItem == 0) 1 else 0

    }


}